const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const usersCollection = db.collection('users')

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { openid } = wxContext
  const { avatarUrl, nickName } = event

  try {
    // 更新用户基础信息
    const updateResult = await usersCollection.where({
      _openid: openid
    }).update({
      data: {
        avatarUrl: avatarUrl || '',
        nickName: nickName || '微信用户',
        updatedAt: new Date()
      }
    })

    if (updateResult.stats.updated > 0) {
      // 获取更新后的用户信息
      const userResult = await usersCollection.where({
        _openid: openid
      }).get()

      return {
        success: true,
        data: userResult.data[0],
        message: '用户信息同步成功'
      }
    } else {
      // 如果用户不存在，创建新用户
      const newUserInfo = {
        _openid: openid,
        avatarUrl: avatarUrl || '',
        nickName: nickName || '微信用户',
        memberLevel: '普通会员',
        balance: 0,
        totalPoints: 0,
        createdAt: new Date(),
        updatedAt: new Date()
      }

      await usersCollection.add({
        data: newUserInfo
      })

      return {
        success: true,
        data: newUserInfo,
        message: '新用户信息创建成功'
      }
    }
  } catch (error) {
    console.error('同步用户信息失败:', error)
    return {
      success: false,
      error: error.message,
      message: '同步用户信息失败'
    }
  }
}